<script>
import {
  updateProfile,
  getArticle,
  updatePopular,
} from "../../api/otherServer";
import { mapGetters, mapActions } from "vuex";
import { statcUrl } from "../../api/api";
import { getDetail } from "../../api/otherServer";
import { formatDate } from "../../util/tool";
import { Notify } from "vant";
import { Dialog } from "vant";
export default {
  props: ["id"],
  data() {
    return {
      dataes: [],
      statcUrl,
      selectColor: "",
      selectSize: "",
      showPicker: false,
      showSize: false,
      arctileList: [],
    };
  },
  mounted() {
    this.getProDetail();
    this.getAt();
    updatePopular({ id: this.id }, (res) => {});
  },
  computed: {
    ...mapGetters("usermessage", ["getProfile", "shoppNum"]),
    images() {
      return this.dataes.img?.split(",") || [];
    },
    color() {
      let data = this.dataes.color?.split(",");
      if (data) {
        this.selectColor = data[0];
      }
      return data;
    },
    size() {
      let data = this.dataes.size?.split(",");
      if (data) {
        this.selectSize = data[0];
      }
      return data;
    },
    detail() {
      let dataDetil = this.dataes.detail;
      // 利用正则将图片取出来
      let reg = /src="\/apidoc\/vapi/g;
      dataDetil = dataDetil?.replace(reg, `src="${statcUrl}/vapi`) || "";
      // console.log(dataDetil);
      return dataDetil;
    },
  },
  methods: {
    ...mapActions("usermessage", ["setprofileActions"]),
    getProDetail() {
      getDetail({ id: this.id }, (res) => {
        this.dataes = res.data[0].data[0];
      });
    },
    dataGs(str) {
      return formatDate(str);
    },
    //获取商品的评价
    getAt() {
      getArticle({ proid: this.id, page: 1 }, (res) => {
        this.arctileList = res.data[0].data;
        console.log(this.arctileList);
      });
    },
    onConfirm(finshData) {
      //选择颜色
      this.showPicker = false;
      this.selectColor = finshData;
    },
    onConfirm2(finshData) {
      //选择尺寸
      this.showSize = false;
      this.selectSize = finshData;
    },

    addCarts() {
      if (!this.getProfile.id) {
        return Dialog.confirm({
          title: "警告",
          message: "请您先进行登录或则注册",
        })
          .then(() => {
            this.$router.push("/login");
          })
          .catch(() => {
            "";
          });
      }
      let { shoppingcart } = this.getProfile;
      if (shoppingcart) {
        //判断shoppcart里面有没有字段有的话则将其解析出来没有的话让其成为一个空数组
        shoppingcart = JSON.parse(shoppingcart);
      } else {
        shoppingcart = [];
      }
      //判断商品的唯一性如果一样的商品购物车的数据不能一直递增，让其自身的数量增加一就好了
      let inCart = false;
      for (let i = 0; i < shoppingcart.length; i++) {
        if (
          shoppingcart[i].size == this.selectSize &&
          shoppingcart[i].color == this.selectColor &&
          shoppingcart[i].id == this.id
        ) {
          shoppingcart[i].num++;
          inCart = true;
          break;
        }
      }
      //点击的时候给shoppingcart添加数据
      if (!inCart) {
        shoppingcart.push({
          id: this.id,
          color: this.selectColor,
          size: this.selectSize,
          img: this.images[0],
          num: 1,
          creatTime: new Date().getTime(),
          title: this.dataes.title,
          price: (this.dataes.price * this.dataes.discount).toFixed(2),
        });
      }

      // 把更新的数据更新到后端和store状态
      updateProfile(
        {
          filedname: "shoppingcart",
          filedvalue: JSON.stringify(shoppingcart),
        },
        () => {
          //更新到store状态
          this.setprofileActions({
            data: {
              ...this.getProfile,
              shoppingcart: JSON.stringify(shoppingcart),
            },
          });
          Notify({ type: "success", message: "添加成功" });
        }
      );
    },
  },
};
</script>
<template>
  <van-nav-bar
    title="商品详情"
    left-text="返回"
    left-arrow
    @click-left="this.$router.replace('/list')"
    placeholder
    fixed
  />
  <van-swipe :autoplay="3000" lazy-render>
    <van-swipe-item v-for="image in images" :key="image.key">
      <img :src="statcUrl + '/' + image" style="width: 100%" />
    </van-swipe-item>
  </van-swipe>
  <div class="product-container">
    <h3>{{ dataes.title }}</h3>
    <p v-if="dataes.brand" class="brand">{{ dataes.brand }}</p>
    <div class="price">
      <span>￥{{ (dataes.price * dataes.discount).toFixed(2) }}</span>
      <span
        ><del>{{ dataes.price }}</del>
      </span>
    </div>
  </div>
  <div class="pro_message">
    <div class="div" @click="showPicker = true">
      <div v-if="color">
        <span class="All_right">颜色:</span>
        <span>{{ selectColor }} </span>
      </div>
      <van-icon name="arrow" class="van-font" />
    </div>
    <div class="div" @click="showSize = true">
      <div v-if="size">
        <span class="All_right">尺码:</span>
        <span>{{ selectSize }} </span>
      </div>
      <van-icon name="arrow" class="van-font" />
    </div>
  </div>
  <div class="pro_message">
    <div class="div">
      <div>
        <span class="All_right">销量:</span>
        <span>{{ dataes.sales }} </span>
      </div>
    </div>
    <div class="div">
      <div>
        <span class="All_right">库存:</span>
        <span>{{ dataes.stock }} </span>
      </div>
    </div>
  </div>
  <div class="pro_message">
    <div class="div">
      <div>
        <span>用户评价:</span>
      </div>
      <div>
        <span class="All-color">查看全部 </span>
        <van-icon name="arrow" class="van-font" />
      </div>
    </div>
    <div class="evaluate_container" v-for="item in arctileList" :key="item.id">
      <div>
        <div class="user_message">
          <figure class="user_avator">
            <img :src="statcUrl + '/' + item.avatar" alt="" />
          </figure>
          <p class="user_name">{{ item.nick }}</p>
        </div>

        <div class="release_time">{{ dataGs(item.createtime) }}</div>
      </div>
      <p><van-rate v-model="item.score" /></p>
      <p class="evaluate_content">{{ item.text }}</p>
    </div>
  </div>
  <div class="container" v-html="detail"></div>
  <div class="container_hidden"></div>
  <div class="purchase_container">
    <div>
      <span class="iconfont icon-zixun"></span>
      <p>咨询</p>
    </div>
    <div>
      <span class="iconfont icon-shoucang"></span>
      <p>收藏</p>
    </div>

    <div @click="$router.push('/cart?id=detail')">
      <van-badge :content="shoppNum" :show-zero="false">
        <span class="iconfont icon-gouwuche"></span>
        <p>购物车</p>
      </van-badge>
    </div>

    <div @click="addCarts">加入购物车</div>
  </div>
  <van-popup v-model:show="showPicker" round position="bottom">
    <van-picker
      v-if="color"
      :columns="color"
      @cancel="showPicker = false"
      @confirm="onConfirm"
    />
  </van-popup>
  <van-popup v-model:show="showSize" round position="bottom">
    <van-picker
      v-if="size"
      :columns="size"
      @cancel="showSize = false"
      @confirm="onConfirm2"
    />
  </van-popup>
</template>
<style src="./index.scss"></style>
